package com.rc.saas.tenant.controller.invoice;

import com.alibaba.excel.EasyExcel;
import com.github.pagehelper.PageInfo;
import com.rc.saas.tenant.base.WebPageInfo;
import com.rc.saas.tenant.common.utils.BeanUtil;
import com.rc.saas.tenant.common.utils.StringUtil;
import com.rc.saas.tenant.common.vo.TResponse;
import com.rc.saas.tenant.model.elec.ElecStation;
import com.rc.saas.tenant.model.elec.ElecStationExample;
import com.rc.saas.tenant.model.tenant.TenantUser;
import com.rc.saas.tenant.search.invoice.InvoiceSearch;
import com.rc.saas.tenant.service.elec.ElecStationService;
import com.rc.saas.tenant.service.invoice.InvoiceApplyService;
import com.rc.saas.tenant.service.operator.TenantOperatorOpenServiceService;
import com.rc.saas.tenant.service.operator.TenantOperatorStationService;
import com.rc.saas.tenant.shiro.ShiroUtils;
import com.rc.saas.tenant.vo.elec.TenantOperatorStationVo;
import com.rc.saas.tenant.vo.invoice.CountInvoice;
import com.rc.saas.tenant.vo.invoice.InvoiceApplyResultVo;
import com.rc.saas.tenant.vo.invoice.InvoiceProxyStationSearchVo;
import com.rc.saas.tenant.vo.order.OrderPrintVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author frog
 * @date 2021/8/12
 */
@Controller
@RequestMapping("/invoiceProxyStation")
public class InvoiceProxyStationController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private ElecStationService elecStationService;

    @Autowired
    private TenantOperatorStationService tenantOperatorStationService;

    @Autowired
    private InvoiceApplyService invoiceApplyService;

    @Autowired
    private TenantOperatorOpenServiceService tenantOperatorOpenServiceService;

    /**
     * 跳转代开发票站点页面
     *
     * @return
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index(Model model) {
        TenantUser user = ShiroUtils.getSessionUser();
        ElecStationExample example = new ElecStationExample();
        example.createCriteria().andProxyTypeEqualTo("0").andTenantCodeEqualTo(user.getTenantCode())
                .andHlhtOperatorIdIsNull().andHlhtStationNoIsNull();
        List<ElecStation> elecStations = elecStationService.selectByExample(example);
        model.addAttribute("elecStations", elecStations);
        return "/templates/invoice/invoiceProxyStation";
    }


    /**
     * 返回代开发票站点列表数据
     *
     * @return
     */
    @RequestMapping(value = "/listPageInvoiceProxyStation", method = RequestMethod.GET)
    @ResponseBody
    public WebPageInfo listPageInvoiceProxyStation(InvoiceProxyStationSearchVo invoiceProxyStationSearchVO) {
        PageInfo<ElecStation> pageInfo = elecStationService.listPageInvoiceProxyStation(invoiceProxyStationSearchVO);
        WebPageInfo webPageInfo = new WebPageInfo(pageInfo.getList(), Long.valueOf(pageInfo.getTotal()).intValue());
        return webPageInfo;
    }

    /**
     * 添加代开发票站点
     *
     * @return
     */
    @RequestMapping(value = "/saveInvoiceProxyStation", method = RequestMethod.POST)
    @ResponseBody
    public TResponse saveInvoiceProxyStation(Long elecStationId) {
        try {
            TenantUser user = ShiroUtils.getSessionUser();
            ElecStation elecStation = new ElecStation();
            elecStation.setElecStationId(elecStationId);
            elecStation.setProxyType("1");
            elecStation.setInvoiceProxyTime(new Date());
            elecStation.setInvoiceProxyTenantCode(user.getTenantCode());
            elecStationService.updateByPrimaryKeySelective(elecStation);
            return TResponse.SUCCESS();
        } catch (Exception e) {
            logger.error("添加代开发票站点失败", e);
            return TResponse.FAIL("操作失败");
        }
    }


    /**
     * 取消代开发票站点
     *
     * @return
     */
    @RequestMapping(value = "/updateInvoiceProxyStationStatus", method = RequestMethod.POST)
    @ResponseBody
    public TResponse updateInvoiceProxyStationStatus(Long elecStationId) {
        try {
            ElecStation elecStation = new ElecStation();
            elecStation.setElecStationId(elecStationId);
            elecStation.setProxyType("0");
            elecStationService.updateByPrimaryKeySelective(elecStation);
            return TResponse.SUCCESS();
        } catch (Exception e) {
            logger.error("取消代开发票站点失败", e);
            return TResponse.FAIL("操作失败");
        }
    }

    /**
     * 获取对应站点的分销商
     *
     * @return
     */
    @RequestMapping(value = "/listOperatorByStationId", method = RequestMethod.GET)
    @ResponseBody
    public TResponse listOperatorByStationId(Long elecStationId) {
        try {
            ElecStation elecStation = elecStationService.selectByPrimaryKey(elecStationId);
            List<TenantOperatorStationVo> tenantOperatorStations = tenantOperatorStationService.listOperatorByStationId(elecStationId);

            for (TenantOperatorStationVo tenantOperatorStation : tenantOperatorStations) {
                tenantOperatorStation.setSelect("1");
                if (StringUtil.isNotBlank(elecStation.getInvoiceProxyTenantCode())) {
                    if (elecStation.getInvoiceProxyTenantCode().equals(tenantOperatorStation.getTenantOperatorCode())) {
                        tenantOperatorStation.setSelect("0");
                    }
                }
            }

            return TResponse.SUCCESS_DATA(tenantOperatorStations);
        } catch (Exception e) {
            logger.error("获取对应站点的分销商失败", e);
            return TResponse.FAIL("操作失败");
        }
    }


    /**
     * 保存开票账号设置
     *
     * @return
     */
    @RequestMapping(value = "/saveAccountSetting", method = RequestMethod.POST)
    @ResponseBody
    public TResponse saveAccountSetting(String tenantType, String tenantOperatorCode, Long elecStationId) {
        if (!BeanUtil.isValid(tenantType, elecStationId)) {
            return TResponse.FAIL("请输入正确的参数");
        }
        if ("1".equals(tenantType)) {
            if (StringUtil.isBlank(tenantOperatorCode)) {
                return TResponse.FAIL("请选择分销商账号");
            }
        }

        TenantUser user = ShiroUtils.getSessionUser();
        try {
            ElecStation elecStation = elecStationService.selectByPrimaryKey(elecStationId);
            return tenantOperatorStationService.saveAccountSetting(tenantType, tenantOperatorCode, user, elecStation);
        } catch (Exception e) {
            logger.error("保存开票账号设置失败", e);
            return TResponse.FAIL("操作失败");
        }
    }


    /**
     * 跳转开票记录页面
     *
     * @return
     */
    @RequestMapping(value = "/invoiceRecord/{elecStationId}", method = RequestMethod.GET)
    public String invoiceRecord(@PathVariable("elecStationId") Long elecStationId, Model model) {
        model.addAttribute("elecStationId", elecStationId);
        return "/templates/invoice/invoiceRecord";
    }


    /**
     * 返回开票记录列表数据
     *
     * @return
     */
    @RequestMapping(value = "/listPageInvoiceRecord", method = RequestMethod.GET)
    @ResponseBody
    public WebPageInfo listPageInvoiceRecord(InvoiceSearch invoiceSearch) {
        PageInfo<InvoiceApplyResultVo> pageInfo = invoiceApplyService.listPageInvoiceApplyByProxy(invoiceSearch);
        WebPageInfo webPageInfo = new WebPageInfo(pageInfo.getList(), Long.valueOf(pageInfo.getTotal()).intValue());
        return webPageInfo;
    }


    /**
     * 获取站点发票总览数
     *
     * @return
     */
    @RequestMapping(value = "/countInvoiceByStation", method = RequestMethod.GET)
    @ResponseBody
    public TResponse countInvoiceByStation(Long elecStationId) {
        try {
            TenantUser user = ShiroUtils.getSessionUser();
            CountInvoice countInvoice = invoiceApplyService.countInvoiceByStation(elecStationId, user.getTenantCode(), user.getTenantOperatorCode());
            return TResponse.SUCCESS_DATA(countInvoice);
        } catch (Exception e) {
            logger.error("获取站点发票总览数失败", e);
            return TResponse.FAIL("操作失败");
        }
    }


    /**
     * 批量导出发票订单
     */
    @ResponseBody
    @RequestMapping("/exportInvoiceApply")
    public TResponse exportInvoiceApply(@RequestParam(value = "invoiceApplyList") List<Long> invoiceApplyList, HttpServletResponse response) {
        try {
            ArrayList<OrderPrintVo> list = new ArrayList<>();
            for (Long invoiceApplyId : invoiceApplyList) {
                List<OrderPrintVo> orderPrintVos = invoiceApplyService.exportInvoiceOrder(invoiceApplyId);
                list.addAll(orderPrintVos);
            }
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("订单列表", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), OrderPrintVo.class).sheet("订单列表").doWrite(list);
            return TResponse.SUCCESS();
        } catch (Exception e) {
            logger.error("导出订单失败", e.getMessage());
            return TResponse.FAIL(e.getMessage());
        }
    }


    /**
     * 跳转开票记录页面(分销商)
     *
     * @return
     */
    @RequestMapping(value = "/invoiceRecord/operator", method = RequestMethod.GET)
    public String invoiceRecordOperator() {
        return "/templates/invoice/invoiceRecordOperator";
    }


    /**
     * 返回开票记录列表数据(分销商)
     *
     * @return
     */
    @RequestMapping(value = "/listPageInvoiceRecord/operator", method = RequestMethod.GET)
    @ResponseBody
    public WebPageInfo listPageInvoiceRecordOperator(InvoiceSearch invoiceSearch) {
        TenantUser tenantUser = ShiroUtils.getSessionUser();
        invoiceSearch.setTenantOperatorCode(tenantUser.getTenantOperatorCode());
        PageInfo<InvoiceApplyResultVo> pageInfo = invoiceApplyService.listPageInvoiceApplyByProxy(invoiceSearch);
        WebPageInfo webPageInfo = new WebPageInfo(pageInfo.getList(), Long.valueOf(pageInfo.getTotal()).intValue());
        return webPageInfo;
    }
}
